$(document).ready(function() {

	$("*").find("a[href='"+window.location.href+"']").each(function(){
		$(this).addClass("current");
	});


	$(".errors").click(function(){
		$(".errors").hide();
	});
	$(".success").click(function() {
		$(".success").hide();
	});
	$('.formErrorMessage').click(function(){
		$('.formErrorMessage').hide();
	});
	$('.formSuccessMessage').click(function(){
		$('.formSuccessMessage').hide();
	});
	//proccess addcontent.phtml page on checkboxes
	if($('#publish_content').attr('checked')==true){
		$('#datepicker').attr("disabled",true);
		$('#datepicker').css("background","grey");
		$("#publish_on_date").attr("disabled",true);
		$("#publish_on_date").attr("checked",false);
	} else {
		if($('#publish_on_date').attr('checked')==true){
			$('#datepicker').attr("disabled",false);
			$('#datepicker').css("background","#FFE45C");
			$("#publish_on_date").attr("disabled",false);
		} else {
			$('#datepicker').attr("disabled",true);
			$('#datepicker').css("background","grey");
			$("#publish_on_date").attr("disabled",false);
		}
	}
	$('#publish_content').click(function() {
		if($('#publish_content').attr('checked')==true){
			$('#datepicker').attr("disabled",true);
			$('#datepicker').css("background","grey");
			$('#datepicker').val("");
			$("#publish_on_date").attr("checked",false);
			$("#publish_on_date").attr("disabled",true);
		} else {
			$('#datepicker').attr("disabled",true);
			$("#publish_on_date").attr("disabled",false);
		}
	});
	$('#publish_on_date').click(function() {
		if($('#publish_on_date').attr('checked')==true){
			$('#datepicker').attr("disabled",false);
			$('#datepicker').css("background","#FFE45C");
			$('#datepicker').datepicker("setDate", new Date());
		} else {
			$('#datepicker').attr("disabled",true);
			$('#datepicker').css("background","grey");
			$('#datepicker').val("");
		}
	});
	/*
 *END proccess the add new page
 **/
	$('#editContentForm, #addContentForm').submit(function(){
		var content         = $('#admincontentarea').val();
		var publish_content = $('#publish_content').attr('checked');
		var publish_on_date = $('#publish_on_date').attr('checked');
		var datepicker      = $('#datepicker').val();
		var ctype           = $('#ctype').val();
        var blog            = $('#blog').val();
		var ajxMessage      = $('#ajaxcontentmsg');
		publish_content = (publish_content == true) ? 1 : 0;
		publish_on_date = (publish_on_date == true) ? 1 : 0;
		$.ajax({
			type: 'post',
			url: this.action,
			data: {
				admincontentarea: content,
				publish_content : publish_content,
				publish_on_date : publish_on_date,
				datepicker      : datepicker,
				ctype           : ctype,
				blog            : blog
			},
			beforeSend: function() {
				ajxMessage.html('Working, please wait...');
				ajxMessage.show();
			},
			success: function(response) {
				if(response == 'success') {
					top.location.reload();
				}
				else {
					ajxMessage.addClass('errors');
					ajxMessage.html('Something went wron. Please retry.');
				}
			}
		});
		return false;
	})

	$('#edit404').click(function() {
        var wsUrl = $('#hid-main-wsurl').val();
        $.ajax({
            type: 'post',
            url: wsUrl + "sys/backend_page/checkopt",
			data: {
				type: '404page'
			},
            success: function(response) {
                if(response == 'fail') {
                    alert('404 Page does not exists. You should create it.');
                } else {
                    top.location = response;
                }
            }
        });
    })

	//show/hide frontadmin panel
	$('#showhide').click(function(){
		$('#admincpanel').toggle();
	});
	$('#cantDeletePage').animate({
		opacity: 0
	}, 6000,  function(){
		$('#cantDeletePage').hide()
	});
	//edit and add form submition
	$('#addHeader, #editHeader').submit(function(){
		//content = encodeURIComponent($(':input:textarea').val());
		content = ($('#editheader').val());
		var ctype = $('#ctype').val();
		jQuery.ajax({
			type: "post",
			url: this.action,
			data: {
			   admincontentarea:content,
			   ctype:ctype
			},
			success: function(response) {
				if(response == 'success') {
					top.location.reload();
				}
			}
		});
		return false;
	})

	$('.pc_list_item, .pb_list_item').click(function(e){
	    e.preventDefault();
	    var urlwebsite = $('#hid-main-wsurl').val();
	    var filer = $(this).text();
	    var href = $(this).attr('href');
	    $.ajax({
		type : 'post',
		url : urlwebsite +'sys/backend_ajax/storeprodfilter',
		data : ({
		    productFilter: filer
		}),
		success: function(){
		    window.location.href = href;
		}
	    });
	})
})




function showDiv(param)
{
    switch(param)
    {
        case 'small':
                $("#images_medium").removeClass("show_div");
                $("#images_large").removeClass("show_div");
                $("#images_original").removeClass("show_div");
                $("#list_files").removeClass("show_div");
                $("#content_variables_maker").removeClass("show_div");
                $("#images_small").toggleClass("show_div");
                break;
        case 'medium':
                $("#images_small").removeClass("show_div");
                $("#images_large").removeClass("show_div");
                $("#images_original").removeClass("show_div");
                $("#list_files").removeClass("show_div");
                $("#content_variables_maker").removeClass("show_div");
                $("#images_medium").toggleClass("show_div");
                break;
        case 'large':
                $("#images_medium").removeClass("show_div");
                $("#images_small").removeClass("show_div");
                $("#images_original").removeClass("show_div");
                $("#list_files").removeClass("show_div");
                $("#content_variables_maker").removeClass("show_div");
                $("#images_large").toggleClass("show_div");
                break;
        case 'files':
                $("#images_medium").removeClass("show_div");
                $("#images_small").removeClass("show_div");
                $("#images_large").removeClass("show_div");
                $("#images_original").removeClass("show_div");
                $("#content_variables_maker").removeClass("show_div");
                $("#list_files").toggleClass("show_div");
                break;
        case 'original':
                $("#images_medium").removeClass("show_div");
                $("#images_small").removeClass("show_div");
                $("#images_large").removeClass("show_div");
                $("#list_files").removeClass("show_div");
                $("#content_variables_maker").removeClass("show_div");
                $("#images_original").toggleClass("show_div");
                break;
        case 'variables_maker':
                $("#images_medium").removeClass("show_div");
                $("#images_small").removeClass("show_div");
                $("#images_large").removeClass("show_div");
                $("#images_original").removeClass("show_div");
                $("#list_files").removeClass("show_div");
                $("#content_variables_maker").toggleClass("show_div");
                break;
        default:
                break;
    }
}

function loadImages(urlwebsite, folder)
{
    $.ajax({
        type : 'POST',
        url:''+urlwebsite+'sys/backend_ajax/loadimagesforeditcontent/',
        data: ({folder : folder, textarea: 'admincontentarea'}),
        dataType: 'json',
        success: function(object){
                $("#images_small").html(object.small);
                $("#images_medium").html(object.medium);
                $("#images_large").html(object.large);
                $("#images_original").html(object.original);
        }
    });
}

function loadImagesForRemoveThings(urlwebsite, folder)
{
    $.ajax({
        type : 'POST',
        url:''+urlwebsite+'sys/backend_ajax/loadimagesforremovethings/',
        data: ({folder : folder}),
        dataType: 'html',
        success: function(data){
            $("#removethings_images").html(data);
        }
    });
}

function insertFeaturedAreasInContent(form)
{
	var regDigit = /^([0-9]{1,10})$/;
	var elm = form.list_featured_areas;
	var name = elm.options[elm.selectedIndex].value;
	var max = form.featured_areas_max.value;
	var max_characters = form.featured_areas_max_characters.value;
	var errors = new Array();
	if(name == '') {
		errors.push(1);elm.style.border ='1px solid red';
	} else {
		elm.style.border ='1px solid #ccc';
	}

	if(!max.match(regDigit) || max <= 0) {
		errors.push(1);form.featured_areas_max.style.border ='1px solid red';
	} else {
		form.featured_areas_max.style.border ='1px solid #ccc';
	}

	if(!max_characters.match(regDigit) || max_characters <= 0) {
		errors.push(1);form.featured_areas_max_characters.style.border ='1px solid red';
	} else {
		form.featured_areas_max_characters.style.border ='1px solid #ccc';
	}

	if(errors.length > 0) {
		return;
	}
	var str = '{$featuredarea'+(form.featured_areas_img.checked == true?'img':'')+':';
	str += name+':';
	str += (max > 0?max+':':'4:');
	str += (max_characters > 0?max_characters:'200');
	str += (form.featured_areas_random.checked == true?':random':'')+'}'
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}
function insertFeaturedPageInContent(form){
        var regDigit = /^([0-9]{1,10})$/;
	var elm = form.list_featured_pages;
	var name = elm.options[elm.selectedIndex].value;
	var max_characters = form.featured_page_max_characters.value;
	var errors = new Array();
	if(name == '') {
		errors.push(1);elm.style.border ='1px solid red';
	} else {
		elm.style.border ='1px solid #ccc';
	}

	if(!max_characters.match(regDigit) || max_characters <= 0) {
		errors.push(1);form.featured_page_max_characters.style.border ='1px solid red';
	} else {
		form.featured_page_max_characters.style.border ='1px solid #ccc';
	}

	if(errors.length > 0) {
		return;
	}
	var str = '{$page:'+name+':'+(form.featured_page_img.checked == true?'1':'0')+':';
	str += (max_characters > 0?max_characters:'200')+'}';
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);

}

function insertExternalRSS(form)
{
	var regDigit = /^([0-9]{1,10})$/;
	var url = form.url.value;
	var maxResult = form.max_result.value;
	var maxCharacters = form.max_characters.value;

	var errors = new Array();
	if(url == '') {
		errors.push(1);form.url.style.border ='1px solid red';
	} else {
		form.url.style.border ='1px solid #ccc';
	}

	if(!maxResult.match(regDigit) || maxResult <= 0) {
		errors.push(1);form.max_result.style.border ='1px solid red';
	} else {
		form.max_result.style.border ='1px solid #ccc';
	}

	if(maxCharacters!=""){
		if(!maxCharacters.match(regDigit) || maxCharacters <= 0) {
			errors.push(1);form.max_characters.style.border ='1px solid red';
		} else {
			form.max_characters.style.border ='1px solid #ccc';
		}
	}
	if(errors.length > 0) {
		return;
	}
	url = url.replace("http://", "");
	url = url.replace("https://", "");
	var str = '{$xrss:';
	str += url+':';
	str += maxResult;
	str += (maxCharacters > 0?':'+maxCharacters+'}':'}');
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}

function insertRelatedInContent(form)
{
	var regDigit = /^([0-9]{1,10})$/;
	var keywords = form.related_count_keywords.value;
	var max = form.related_max.value;
	var errors = new Array();
	if(!keywords.match(regDigit) || keywords <= 0) {
		errors.push(1);form.related_count_keywords.style.border ='1px solid red';
	} else {
		form.related_count_keywords.style.border ='1px solid #ccc';
	}
	if(!max.match(regDigit) || max <= 0) {
		errors.push(1);form.related_max.style.border ='1px solid red';
	} else {
		form.related_max.style.border ='1px solid #ccc';
	}
	if(errors.length > 0) {
		return;
	}
	var str = '{$related'+(form.related_img.checked == true?'img':'')+':';
	str += keywords+':';
	str += (max > 0?max:'4')+'}';
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}

function insertSwapper(form)
{
	var regDigit = /^([0-9]{1,10})$/;
	var folder = form.folder.options[form.folder.selectedIndex].value;
	var time = form.time.value;
	var imgWidth = form.imgWidth.value;
	var imgHeight = form.imgHeight.value;
	var errors = new Array();
	if(!imgWidth.match(regDigit) && imgWidth != '') {
		errors.push(1);form.imgWidth.style.border ='1px solid red';
	}
	if(imgWidth == '' || imgWidth == 0) {
		imgWidth = 100;
	}
	if(folder == '') {
		errors.push(1);form.folder.style.border ='1px solid red';
	} else {
		form.folder.style.border ='1px solid #ccc';
	}
	if(form.slideshow.checked == true && (!time.match(regDigit)  && time!='' || time <= 0) ) {
		errors.push(1);
		form.time.style.border ='1px solid red';
	} else {
		form.time.style.border ='1px solid #ccc';
	}

	if(imgHeight=='' || imgHeight==0){
		imgHeight = imgWidth;
	}

	if(errors.length > 0) {
		return;
	}
	var str = '{$imgrotator:'+folder+':'+(form.slideshow.checked == true?'1:'+time:'0:0')+':'+ imgWidth +':'+ imgHeight +'}';
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}

function insertPagesList(form)
{

	var category = form.categories.options[form.categories.selectedIndex].value;

	var errors = new Array();
	if(category == '') {
		errors.push(1);form.categories.style.border ='1px solid red';
	} else {
		form.categories.style.border ='1px solid #ccc';
	}

	if(errors.length > 0) {
		return;
	}
	var str = '{$pageslist:'+category+':'+(form.pagesWithImage.checked == true?'1':'0')+'}';
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}

function insertVariableGallery(form)
{
    var elmFolder = document.getElementById("gallery-list-folder");
    var folder = elmFolder.options[elmFolder.selectedIndex].value;
    var elmThumbnailsSize = document.getElementById("gallery-thumbnails-size");
    var thumbnailsSize = elmThumbnailsSize.value;
    var crop = document.getElementById("gallery-crop").checked == true ? 1 : 0;
    var caption = document.getElementById("gallery-caption").checked == true ? 1 : 0;
    var cooliris = document.getElementById("gallery-cooliris").checked == true ? 1 : 0;
    if (cooliris == 1) {
        var width = document.getElementById("gallery-cooliris-width").value;
        var height = document.getElementById("gallery-cooliris-height").value;
        var elmStyle = document.getElementById("gallery-style");
        var style = elmStyle.options[elmStyle.selectedIndex].value;
        var elmRows = document.getElementById("gallery-rows");
        var rows = elmRows.options[elmRows.selectedIndex].value;
        cooliris += ':'+width+':'+height+':'+style+':'+rows;
    }
    var errors = new Array();

    folder = folder.replace(/^\s+/g, '');
    folder = folder.replace(/\s+$/g, '');

    if (folder != '') {
        elmFolder.style.border = '1px solid #ccc';
    } else {
        errors.push(1);elmFolder.style.border = '1px solid red';
    }

    if (/^([0-9]{1,10})$/.test(thumbnailsSize)) {
        elmThumbnailsSize.style.border = '1px solid #ccc';
    } else {
        errors.push(1);elmThumbnailsSize.style.border = '1px solid red';
    }

    if (errors.length == 0) {
        var variable = '{$gal:'+folder+':'+thumbnailsSize+':'+crop+':'+caption+':'+cooliris+'}';
        $('textarea.tinymce').tinymce().execCommand('mceInsertContent', false, variable);
    }
}

/*
function insertGallery(form, urlwebsite)
{
    var ltrim = /^\s+/g;
    var rtrim = /\s+$/g;
    var regDigit = /^([0-9]{1,10})$/;
    var new_gallery = form.gallery_name.value;
    new_gallery = new_gallery.replace(ltrim,'');
    new_gallery = new_gallery.replace(rtrim,'');
    var elm = form.list_galleries;
    var t_elm = form.gallery_thumbnails;
    var thumbnails = t_elm.value;
    var name;
    if(new_gallery != ''){
            name = new_gallery;
    }else {
            name = elm.options[elm.selectedIndex].value;
    }
    var errors = new Array();
    if(name == '') {
            errors.push(1);elm.style.border ='1px solid red';
    } else {
            elm.style.border ='1px solid #ccc';
    }
    if(!thumbnails.match(regDigit) || thumbnails <= 0) {
            errors.push(1);t_elm.style.border ='1px solid red';
    } else {
            t_elm.style.border ='1px solid #ccc';
    }
    if(errors.length > 0) {
            return;
    }

    $.ajax({
            type : 'POST',
            url:''+urlwebsite+'sys/backend_ajax/savesettingsforgallery/',
            data: ({
                    gallery : name,
                    thumbnails : thumbnails,
                    crop : form.gallery_crop.checked,
                    lightbox : form.gallery_lightbox.checked,
                    caption : form.gallery_caption.checked
            }),
            dataType: 'html',
            success: function(data){
                    if(data != '')
                    {
                            var obj = eval('('+data+')');
                            if(obj.save) {
                                    form.gallery_name.value = '';
                            }
                            if(obj.new_gallery) {
                                    name = obj.gallery;elm.options[elm.length] = new Option(name, name, false, true);
                            }
                            elm.disabled='';
                            var str = '{$gallery:'+name+'}';
                            $('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
                    }
            }
    });
}
*/
function insertCoolirisWall(form){
        var regDigit = /^([0-9]{1,10})$/;
	var elm = form.list_galleries_for_wall;
	var name = elm.options[elm.selectedIndex].value;
	var width = (form.cooliris_wall_width.value!==''?form.cooliris_wall_width.value:'0');
        var height = (form.cooliris_wall_height.value!==''?form.cooliris_wall_height.value:'0');
	var errors = new Array();
	if(name == '') {
		errors.push(1);elm.style.border ='1px solid red';
	} else {
		elm.style.border ='1px solid #ccc';
	}

	if(!width.match(regDigit) || width < 0) {
		errors.push(1);form.cooliris_wall_width.style.border ='1px solid red';
	} else {
		form.cooliris_wall_width.style.border ='1px solid #ccc';
	}

        if(!height.match(regDigit) || height < 0) {
		errors.push(1);form.cooliris_wall_height.style.border ='1px solid red';
	} else {
		form.cooliris_wall_height.style.border ='1px solid #ccc';
	}

	if(errors.length > 0) {
		return;
	}
	var str  = '{$cooliris:'+name;
            str += ':'+(width ? width : '0');
            str += ':'+(height ? height : '0');
            str += ':'+(form.cooliris_wall_rows.value ? form.cooliris_wall_rows.value : '0');
            str += ':'+(form.cooliris_wall_style.value ? form.cooliris_wall_style.value : '0');
            str += '}';
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);

}

function insertForm(form, urlwebsite)
{
	var new_form = form.formname.value;
	var elm = form.forms_list;
	var name="";
	if(new_form != ''){
		name = trim(new_form);
	}else {
		name = trim(elm.options[elm.selectedIndex].value);
	}

	var errors = new Array();
	if(name == '') {
		errors.push(1);elm.style.border ='1px solid red';
	} else {
		elm.style.border ='1px solid #ccc';
	}
	if(errors.length > 0) {
		return;
	}
	var result="";
	if(form.formcaptcha.checked)
	{
		result = '{$form:'+name+':captcha}';
	}else
	{
		result = '{$form:'+name+'}';
	}

	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, result);
}

function insertSearch(form,currentPageId,currentNavName)
{
	var elm = form.pages_list;
	var pageId = trim(elm.options[elm.selectedIndex].value);
	var pageNavName = trim(elm.options[elm.selectedIndex].text);

	if(pageId==-1)
	{
		result = "{$search_form:"+currentPageId+"} <br/><br/>  ======== <b>CODE TO INSERT IN '"+currentNavName+"' page ONLY(remove from here)</b>  ========  <br/>{$search_result} OR {$search_result_img} if you want the results to display page images.<br/> ============================================================== ";
	}else
	{
		result = "{$search_form:"+pageId+"} <br/><br/>  ======== <b>CODE TO INSERT IN '"+pageNavName+"' page ONLY(remove from here)</b>  ========  <br/>{$search_result} OR {$search_result_img} if you want the results to display page images.<br/> ============================================================== ";
	}

	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, result);
}

function loadSettingsForGallery(gallery, form, urlwebsite)
{
	if(gallery == '') {
		form.reset();return;
	}

	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/loadsettingsforgallery/',
		data: ({
			gallery : gallery
		}),
		dataType: 'html',
		success: function(data){
			if(data != '')
			{
				var obj = eval('('+data+')');
				form.gallery_thumbnails.value = obj.thumbnails;
				if(obj.crop=='1'){
					form.gallery_crop.checked=true;
				}else{
					form.gallery_crop.checked=false;
				}
				if(obj.lightbox=='1'){
					form.gallery_lightbox.checked=true;
				}else{
					form.gallery_lightbox.checked=false;
				}
				if(obj.caption=='1'){
					form.gallery_caption.checked=true;
				}else{
					form.gallery_caption.checked=false;
				}
			}
		}
	});
}
function deletePictureInGallery(gallery, image, urlwebsite)
{
	if(gallery == '' || image == '') {
		return;
	}
        $.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/deletepictureingallery/',
		data: ({
			gallery : gallery,
			image : image
		}),
		dataType: 'html',
		success: function(data){
			if(data != '')
			{
				var obj = eval('('+data+')');
				if(obj.del){
					document.getElementById('gallery_image_'+image).style.display = 'none';
				}
				if(obj.delete_folder){
					document.getElementById('gallery_'+gallery).style.display = 'none';
				}
			}
                        //refreshing rss feed for cooliris wall
                        $.ajax({
                            type: 'POST',
                            url: urlwebsite+'sys/backend_gallery/coolirisrss/',
                            data: ({
                                gallery: gallery
                            }),
                            success: function(){}

                        });
		}
	});
}
/*start process comments */

function addComment(containerId,commentId,countToShow,requestedPage,publishedByDefault){

	$('#comment-captcha-invalid-error-'+commentId).hide();
	var websiteUrl = $('#websiteUrl').val();
	var content = encodeURIComponent($('#post-content-'+commentId).val());
	var sign = encodeURIComponent($('#sign-'+commentId).val());
	var email = encodeURIComponent($('#email-'+commentId).val());
	var website = encodeURIComponent($('#website-'+commentId).val());
	var keyword = encodeURIComponent($('#keyword-'+commentId).val());
	var topic = encodeURIComponent($('#topic-'+commentId).val());
	var publishedbydefault = encodeURIComponent($('#publishedbydefault-'+commentId).val());
	var notify = $('#notify-'+commentId).attr('checked');

	var captchaInput = encodeURIComponent($('#captcha-input').val());
	var captchaId = encodeURIComponent($('#captcha-id').val());

    $('.success').ajaxStart(function(){$(this).show().find('#proccessing').show()})
	jQuery.ajax({
		type: "post",
		url: ''+websiteUrl+'sys/backend_ajax/addcomment/',
		data: "content="+content+"&sign="+sign+"&email="+email+"&website="+website+"&containerId="+containerId+"&topic="+topic+"&keyword="+keyword+"&publishedbydefault="+publishedbydefault+"&notify="+notify+"&captcha-input="+captchaInput+"&captcha-id="+captchaId+"&requestedPage="+requestedPage,
        success: function(response) {
			var arr = response.split('~');
            $('#proccessing').hide();

			if(arr[0]!="captacha error")
			{
				if(publishedByDefault==1){
					$('#comments-ol-'+commentId).prepend(arr[0]);
					var olArray  = $('#comments-ol-'+commentId+' li').get();
					if(olArray){
						for(var i =countToShow;i<olArray.length;i++)
						{
							olArray[i].style.display='none';
						}

						if(olArray.length>countToShow)
						{
							$("#commentslinkholder").empty();
							$("#commentslinkholder").html('<a href="javascript:void(0);" onclick="showHideComments(\''+commentId+'\',\''+countToShow+'\');" id="show-all-comments-'+commentId+'"  title="Show All Comments" >Show all comments</a>');
						}

						$('#captcha-input').val('');
						$('#captcha-id').val(arr[1]);
						$('#captcha-image').attr('src',websiteUrl+'tmp/'+arr[1]+'.png');

						$('.success').show();
						$('#added').show();

					}
				}else
				{
					$('#captcha-input').val('');
					$('#captcha-id').val(arr[1]);
					$('#captcha-image').attr('src',websiteUrl+'tmp/'+arr[1]+'.png');
					$('.success').show();
					$('#addedwait').show();
				}

			}else
			{ //capthca error
				hideCommentErrors(commentId);
				$('#sign-'+commentId).val(arr[1]);
				$('#email-'+commentId).val(arr[2]);
				$('#website-'+commentId).val(arr[3]);

				if(arr[4]==1){
					$('#notify-'+commentId).attr('checked',true);
				}


				$('#post-content-'+commentId).val(arr[5]);
				$('#captcha-id').val(arr[6]);
				$('#captcha-image').attr('src',websiteUrl+'tmp/'+arr[6]+'.png');
				$('#comment-errors-'+commentId).show();
				$('#comment-captcha-invalid-error-'+commentId).show();
			}
		//top.location.reload();
		}

	});

	$('#sign-'+commentId).val("");
	$('#email-'+commentId).val("");
	$('#website-'+commentId).val("");
	$('#post-content-'+commentId).val("");
	$('#notify-'+commentId).attr("checked",false);
}

function publishComment(commentId)
{
	var websiteUrl = $('#websiteUrl').val();
	if(commentId>0)
	{
		jQuery.ajax({
			type: "post",
			url: ''+websiteUrl+'sys/backend_ajax/publishcomment/',
			data: "id="+commentId,
			success: function(response) {
				var id;
				if(response.length>20)
				{
					var arr = response.split("<br");
					id = arr[0];
				}else
				{
					id = response;
				}

				$('#comment-item-li-'+id).attr('style','border:1px solid #DDDDDD;');
				$('#publish-link-'+id).empty();
			}
		});
	}

}

function hideCommentErrors()
{
	$(".errors").click(function()
	{
		$(".errors").hide();
	});

	$(".success").click(function()
	{
		$(".success").hide();
	});
/*$('#comment-name-empty-error-'+id).hide();
    $('#comment-email-empty-error-'+id).hide();
    $('#comment-content-empty-error-'+id).hide();
    $('#comment-email-regex-error-'+id).hide();
    $('#comment-captcha-empty-error-'+id).hide();
    $('#comment-errors-'+id).hide();*/
}

function checkPostCommentForm(id)
{
	hideCommentErrors(id);
	var result = true;
	var ltrim = /^\s+/g;
	var rtrim = /\s+$/g;

	document.getElementById('sign-'+id).value = document.getElementById('sign-'+id).value.replace(ltrim,'');
	document.getElementById('sign-'+id).value = document.getElementById('sign-'+id).value.replace(rtrim,'');

	document.getElementById('email-'+id).value = document.getElementById('email-'+id).value.replace(ltrim,'');
	document.getElementById('email-'+id).value = document.getElementById('email-'+id).value.replace(rtrim,'');

	document.getElementById('post-content-'+id).value = document.getElementById('post-content-'+id).value.replace(ltrim,'');
	document.getElementById('post-content-'+id).value = document.getElementById('post-content-'+id).value.replace(rtrim,'');

	document.getElementById('captcha-input').value = document.getElementById('captcha-input').value.replace(ltrim,'');
	document.getElementById('captcha-input').value = document.getElementById('captcha-input').value.replace(rtrim,'');

	if(document.getElementById('sign-'+id).value == '')
	{

		$('#comment-errors-'+id).show();
		$('#comment-name-empty-error-'+id).show();
		result = false;
	}

	if(document.getElementById('email-'+id).value == '')
	{
		$('#comment-errors-'+id).show();
		$('#comment-email-empty-error-'+id).show();
		result = false;

	}else
	{
		var email =  $('#email-'+id).val();
		if(!checkEmail(email))
		{
			$('#comment-errors-'+id).show();
			$('#comment-email-regex-error-'+id).show();
			result = false;
		}
	}

	if(document.getElementById('post-content-'+id).value == '')
	{
		$('#comment-errors-'+id).show();
		$('#comment-content-empty-error-'+id).show();
		result = false;
	}

	if(document.getElementById('captcha-input').value == '')
	{
		$('#comment-errors-'+id).show();
		$('#comment-captcha-empty-error-'+id).show();
		result = false;
	}

	return result;
}

function deleteComment(id)
{
	websiteUrl = $('#hid-main-wsurl').val();

	jQuery.ajax({
		type: "post",
		url: ''+websiteUrl+'sys/backend_ajax/deletecomment/',
		data: "id="+id,
		success: function(response) {
			if(response){
				// $('#comment-'+id).remove();
				top.location.reload();
			}
		}
	});
}

function showHideComments(id,countToShow)
{
	var olArray  = $('#comments-ol-'+id+' li').get();

	if($('#show-all-comments-'+id).html()=='Show all comments')
	{
		for(i=countToShow;i<olArray.length;i++){
			olArray[i].style.display='block';
		}
		$('#comments-ol-'+id+' li div').css('display','block');
		$('#show-all-comments-'+id).empty().append("Hide Comments");
	}
	else
	{
		if($('#show-all-comments-'+id).html()=="Hide Comments")
		{
			for(i=countToShow;i<olArray.length;i++){
				olArray[i].style.display='none';
			}
			$('#show-all-comments-'+id).empty().append("Show all comments");
		}
	}
}

function checkEmail(email)
{
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) {
		return false;
	}else{
		return true;
	}
}

/*end process comments*/

function insertPaymentButtonInContent(form, urlwebsite)
{
	var reg = /^[a-zA-Z0-9_\s-]{1,225}$/;
	var ltrim = /^\s+/g;
	var rtrim = /\s+$/g;
	var elm_name = form.payment_name;
	var elm_list = form.list_payment;
	var elm_content = form.payment_content;
	var content = elm_content.value;
	var name;
	var new_name = elm_name.value;
	new_name = new_name.replace(ltrim,'');
	new_name = new_name.replace(rtrim,'');
	content = content.replace(ltrim,'');
	content = content.replace(rtrim,'');
	if(new_name != '') {
		for(var i=0;i<elm_list.length;i++) {
			if(elm_list.options[i].value == new_name) {
				elm_name.style.border ='1px solid red';
				alert('This name is existed');
				return;
			}
		}
		name = new_name;
	} else {
		name = elm_list.options[elm_list.selectedIndex].value;
	}
	elm_name.style.border ='1px solid #ccc';
	var errors = new Array();
	if(name != '' && name.match(reg)) {
		elm_list.style.border ='1px solid #ccc';
	} else {
		errors.push(1);elm_list.style.border ='1px solid red';
	}
	if(content != '') {
		elm_content.style.border ='1px solid #ccc';
	} else {
		errors.push(1);elm_content.style.border ='1px solid red';
	}
	if(errors.length > 0) {
		return;
	}

	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/insertpaymentbuttonincontent/',
		data: ({
			name : name,
			content : content
		}),
		dataType: 'html',
		success: function(data){
			if(data != ''){
				var obj = eval('('+data+')');
				if(!obj.update) {
					elm_list.options[elm_list.length] = new Option(obj.name, obj.name, false, true);
				}
				elm_name.value = '';
				$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, '{$paymentbutton:'+obj.name+'}');
			}
		}
	});
}

function loadContentForPaymentButton(elm , urlwebsite)
{
	var form = elm.form;
	var name = elm.options[elm.selectedIndex].value;
	if(name == '') {
		form.payment_content.value = '';return;
	}

	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/loadpaymentbuttonbyname/',
		data: ({
			name : name
		}),
		dataType: 'html',
		success: function(data){
			if(data != '') {
				var obj = eval('('+data+')');
				form.payment_content.value =  obj.content;
			}
		}
	});
}

function insertCommentInContent(form, urlwebsite)
{
	var ltrim = /^\s+/g;
	var rtrim = /\s+$/g;
	var regDigit = /^([0-9]{1,10})$/;
	var elm_t = form.comment_topic;
	var elm_k = form.comment_keyword;

	var elm_c = form.comment_count;
	var elm_p = form.comment_publish
	var container_name = form.container_name.value;
	/*
    var topic = elm_t.value;
    topic = topic.replace(ltrim,'');
    topic = topic.replace(rtrim,'');
    var keyword = elm_k.value;
    keyword = keyword.replace(ltrim,'');
    keyword = keyword.replace(rtrim,'');
	*/
	var topic = 'default';
	var keyword = 'default';

	var count = elm_c.value;
	var publish = elm_p.checked;
	var errors = new Array();
	/*if(topic == '' || !topic.match(/^[a-zA-Z0-9_\s-]{1,225}$/)) {
        errors.push(1);elm_t.style.border = '1px solid red';
    } else {
        elm_t.style.border ='1px solid #ccc';
    }
    if(keyword == ''  || !keyword.match(/^[a-zA-Z0-9_-]{1,225}$/)) {
        errors.push(1);elm_k.style.border = '1px solid red';
    } else {
        elm_k.style.border ='1px solid #ccc';
    }*/
	if(!count.match(regDigit) || count<= 0) {
		errors.push(1);elm_c.style.border = '1px solid red';
	} else {
		elm_c.style.border ='1px solid #ccc';
	}
	if(errors.length > 0) {
		return;
	}

	/*$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/insertcommentincontent/',
		data: ({
			topic : topic,
			keyword : keyword
		}),
		dataType: 'html',
		success: function(data){
			if(data != ''){
				var obj = eval('('+data+')');
				if(obj.exist > 0) {
					alert('This keyword already exists.');
					return;
				}
				if(obj.exist == 0) {
					$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, '{$comments:'+container_name+':'+topic+':'+keyword+':'+count+':'+(publish==true?'1':'0')+'}');
				}
			}
		}
	});*/
        $('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, '{$comments:'+container_name+':'+topic+':'+keyword+':'+count+':'+(publish==true?'1':'0')+'}');
}

function deleteUser(url,id, elm)
{
	if(url == '' || id < 0) {
		return;
	}

	$.ajax({
		type : 'POST',
		url:''+url+'sys/backend_ajax/deleteuser/',
		data: ({
			id : id
		}),
		dataType: 'html',
		success: function(data){
			if(data > 0){
				elm.parentNode.parentNode.style.display = 'none';
			}
		}
	});
}

function editUser(url, id)
{
	if(url == '' || id < 0) {
		return;
	}
	var form = document.forms[0];

	$.ajax({
		type : 'POST',
		url:''+url+'sys/backend_ajax/loaduser/',
		data: ({
			id : id
		}),
		dataType: 'html',
		success: function(data){
			var obj = eval('('+data+')');
			if(obj.nickname != ''){
				form.nickname.value = obj.nickname;
				form.login.value = obj.login;
				form.password.value = obj.password;
				form.email.value = obj.email;
				for(var i=0;i<form.role.options.length;i++) {
					if(form.role.options[i].value == obj.role) {
						form.role.options[i].selected = true;
						break;
					}
				}
				form.id.value = id;
				form.submit.value = 'Update';
				document.getElementById('back_adduserform').style.display = 'block';
			}
		}
	});
}


//replace silo spans back to the links
function replaceNSP() {
	siteUrl = $('#hid-main-wsurl').val();
	$.get(siteUrl + "tmp/pfs.prs", function(data){
		if(data == 'forprsculpting') {
			return;
		}
		pIdsUrls = data;
		var toReplace = $.find('span');
		$.each(toReplace, function() {
			if($(this).hasClass('nsp')) {
				pages = eval('(' + unescape(pIdsUrls) + ')');
				//alert(pages);
				var url = '';
				for(var i=0; i<=pages.length-1; i++) {
					if(pages[i].id == $(this).attr('id')) {
						url = pages[i].url;
					}
				}
				$(this).replaceWith('<a href="'+siteUrl + url+'.html">' + $(this).html() + '</a>');
			}
		})
		$("ul#main_menu li ul li a").addClass("page");
	})



}

function utfDecode(utftext)
{

	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length ) {

		c = utftext.charCodeAt(i);

		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}

	}

	return string;
}

function sendRecovering()
{
	hideAllPasswordMessages();
	var urlwebsite = $('#hid-main-wsurl').val();
	var email = trim($('#email').val());
	if(email!="" ){
		if(checkMail(email)){
			$.ajax({
				type : 'POST',
				url:''+urlwebsite+'sys/backend_ajax/sendrecoveringlink/',
				data: ({
					email : email
				}),
				success: function(response){
					switch (response)
					{
						case "success":
							$('#email').val('');
							$('#passwordsuccess').show();
							$('#linksent').show();
							$('.forgotpassword').toggle();
						break;

						case "email does not exist":
							$('#passworderrors').show();
							$('#emailnotexists').show();
						break;

						case "error":
							$('#passworderrors').show();
							$('#notsent').show();
						break;
					}
				}
			});
		}else{
			hideAllPasswordMessages();
			$('#passworderrors').show();
			$('#validemail').show();
		}
	}else{
		hideAllPasswordMessages();
		$('#passworderrors').show();
		$('#emptyemail').show();
	}


}

function showForgotPasswordScreen(){
	$('.forgotpassword').toggle();
	$('.admineditwhat').html("Forgot your password?");
}
function showLoginScreen(){
	$('.forgotpassword').toggle();
    $('.admineditwhat').html("Login");
}

function hideAllPasswordMessages(){
	$('#passworderrors').hide();
	$('#passworderrors ul li').hide();

	$('#passwordsuccess').hide();
	$('#passwordsuccess ul li').hide();

}

function trim(a){a=a.replace(/^\s+/g,"");return a=a.replace(/\s+$/g,"")};

function checkMail(value) {
	reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
	if (!value.match(reg)) {
		return false;
	}else{
		return true;
	}
}

function setHeight(){
		$('#imgHeight').val($('#imgWidth').val());
		$('#imgHeight').select();
	}

function addToCart(id)
{
    if (/^([0-9]{1,10})$/.test(id) && id > 0) {
        var urlwebsite = $('#hid-main-wsurl').val();
        var cartStatus  = $('#usr-cart-widget-status');
        var options = [];
        if(cartStatus.length) {
            cartStatus.ajaxStart(function(){
                $(this).html('Updating cart. Please wait...').show();
            });
        }
        var optsSelects = $('#optholder-' + id).find('select');
        var amount = $('#add-amount-'+id).val();
        if (!/^([0-9]{1,10})$/.test(amount)) {
            amount = 1;
        }
        if(optsSelects.length) {
            $.each(optsSelects, function() {
            var optType = '';
            var optVal  = '';
            $(this).find('option:selected').each(function(){
                optType = $(this).val();
                optVal  = $(this).text();
            })
            options.push(optType + '=' + optVal);
            });
        }
        if ($('#cart-currency').text().length == 3){
            var cartCurrency = $('#cart-currency').text()
        }

        $.ajax({
                type : 'POST',
                url : urlwebsite+'sys/backend_shopping/addtocart/',
                data : ({id:id, opts:options.toString(), amount:amount}),
                dataType : 'json',
                success: function(result) {
                    cartStatus.one('click', function(){
                        var cartCord = $('#usr-cart-widget').position()
                        $(document).scrollTop(cartCord.top);
                        $(this).text('').fadeOut()
                    }).html('Product added. <a href="javascript:;" onclick="storeLastUrl();">Go to cart</a>');
                    window.setTimeout("$('#usr-cart-widget-status').text('').hide()", 3000)
                    $('#usr-cart-widget-quantity').text(result.itemsCount)
                    $('#usr-cart-widget-totalprice').text(result.totalPrice)
                },
                error: function(){
                    cartStatus.one('click', function(){$(this).hide()})
                    cartStatus.text('Unexpected Error. Please, try again.')
                }
            });
    }
}

function removeFromCart(id){
    var urlwebsite = $('#hid-main-wsurl').val();
    var cartStatus  = $('#usr-cart-widget-status');
    if (cartStatus.length) {
        cartStatus.ajaxStart(function(){
            $(this).html('Updating...').show();
        });
    }
    if ($('#cart-currency').text().length == 3){
        var cartCurrency = $('#cart-currency').text()
    }

    $.ajax({
          type : 'POST'
        , url :  urlwebsite+'sys/backend_shopping/recount'
        , data : ({toremove: id})
        , dataType : 'json'
        , success: function(result){
            cartStatus.one('click', function(){
                var cartCord = $('#usr-cart-widget').position()
                $(document).scrollTop(cartCord.top);
                $(this).text('').fadeOut()
            }).text('Product removed');
            window.setTimeout("$('#usr-cart-widget-status').text('').hide()", 3000)
            $('#usr-cart-widget-quantity').text(result.itemsCount)
            $('#usr-cart-widget-totalprice').text(result.totalPrice)
        }
        , error: function(){
            cartStatus.one('click', function(){$(this).hide()})
            cartStatus.text('Unexpected Error. Please, try again.')
        }
    })
}

function recountOrder() {
    var urlwebsite = $('#hid-main-wsurl').val();
    var toRemove = [];
    var toRecount = [];
    var opts = [];
    var remOpts = [];
    var chkbx = $('#cartview-itemsholder').find('input:checkbox:checked');
    var inpToRec = $('#cartview-itemsholder').find('input:text');
    if(chkbx.length) {
	$.each(chkbx, function() {
	    var optClass = $(this).attr('id').replace('todelete-', '');
	    var optsFields = $('#item-' + optClass).find('input:hidden');
	    $.each(optsFields, function(){
		if($(this).hasClass(optClass)) {
		    remOpts.push(optClass + ',' + $(this).val());
		}
	    })
	    toRemove.push($(this).attr('id'));
	})
    }
    if(inpToRec.length) {
	$.each(inpToRec, function() {
	    var optClass = $(this).attr('id').replace('itmcount-', '');
	    var optsFields = $('input:hidden');
	    $.each(optsFields, function(){
		if($(this).hasClass(optClass)) {
		    opts.push(optClass + ',' + $(this).val());
		}
	    })
	    toRecount.push($(this).attr('id')+','+$(this).val());
	})
    }
    $('#startmsg').ajaxStart(function(){
        $(this).html('Updating your cart. Please wait...');
	$(this).show();
    });

    $.ajax({
	type : 'post',
	url : urlwebsite+'sys/backend_shopping/recount',
	data : ({toremove:json_encode(toRemove), torecount:json_encode(toRecount), options: json_encode(opts), remOptions: json_encode(remOpts)}),
	success: function(){
            top.location.reload();
            //countShipping(true);
	}
    });
}
/*
 * AJAX function drawing chart with positions in search engines
 */
function statCall(url, key) {
    var urlwebsite = $('#hid-main-wsurl').val();
    if (url!="" && key!=""){
        var response = '';
        $.ajax({
            type : 'post',
            url : urlwebsite+'sys/backend_page/stat',
            data : ({
                url: url,
                key: key
            }),
            success: function(response){
                $("#statchart").attr("src",response);
            }
        });
    }

}

function storeLastUrl(){
    var urlwebsite = $('#hid-main-wsurl').val();
    var href = window.location.href;
    $.ajax({
        type : 'post',
        url : urlwebsite +'sys/backend_ajax/storelasturl',
        data : ({
            lastUrl: href
        }),
        dataType: 'json',
        success: function(responce){
            if (responce.done) {
                window.location.href=responce.url;
            }
        }
        });
}
